package handlers

import (
	"car-master/cache"
	"car-master/models"
	"car-master/pkg"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if password == "" || username == "" {
		c.JSON(200, gin.H{
			"code": 200,
			"msg":  "字段不能为空",
		})
		return
	}
	reds_key := "reds_log" + username
	reds_count, _ := cache.Rdb.Get(cache.Ctx, reds_key).Int()
	if reds_count >= 3 {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "登录失败三次，禁止登录",
		})
		return
	}
	var user models.User
	err := models.DB.Where("username=?", username).First(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "用户不存在",
		})
		return
	}
	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "用户不存在",
		})
		return
	}
	if pkg.Md5(password) != user.Password {
		cache.Rdb.Incr(cache.Ctx, reds_key)
		if reds_count == 2 {
			cache.Rdb.Set(cache.Ctx, reds_key, 3, time.Hour*2)
			c.JSON(200, gin.H{
				"code": 400,
				"msg":  "登录已锁定，两小时后解锁",
			})
			return
		}
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "账户或密码错误",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登录成功",
		"user": user,
	})
}

func UserList(c *gin.Context) {

	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	pageSize, _ := strconv.Atoi(c.DefaultQuery("pageSize", "5"))
	offset := (page - 1) * pageSize
	if page == 0 || pageSize == 0 {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "字段不能为空",
		})
		return
	}
	/*
		SELECT
		user_lists.id as id,
		user_lists.`name` as Name,
		user_lists.sex as Sex,
		user_lists.`status` as Status,
		user_lists.tel as Tel,
		users.username as Username,
		users.`password` as `Password`
		FROM
		user_lists
		LEFT JOIN users ON users.id=user_lists.id
	*/
	var arr []models.UserKm
	reds_key := "reds_list" + strconv.Itoa(page)
	redsData, _ := cache.Rdb.Get(cache.Ctx, reds_key).Result()
	if redsData == "" {
		models.DB.Table("user_lists").Select(
			"user_lists.id as id",
			"user_lists.`name` as Name",
			"user_lists.sex as Sex",
			"user_lists.`status` as Status",
			"user_lists.tel as Tel",
			"users.username as Username",
			"users.`password` as `Password`",
		).Joins("LEFT JOIN users ON users.id=user_lists.id").
			Offset(offset).Limit(pageSize).Find(&arr)
		jsondata, _ := json.Marshal(arr)
		cache.Rdb.Set(cache.Ctx, reds_key, jsondata, time.Hour*2)
	} else {
		json.Unmarshal([]byte(redsData), &arr)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"list": arr,
	})
}
